﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 车辆图片表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppVehicleImageService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppVehicleImage> _appVehicleImageRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public AppVehicleImageService(SqlSugarRepository<AppVehicleImage> appVehicleImageRep, ISqlSugarClient sqlSugarClient)
    {
        _appVehicleImageRep = appVehicleImageRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询车辆图片表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询车辆图片表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppVehicleImageOutput>> Page(PageAppVehicleImageInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appVehicleImageRep.AsQueryable()
            .WhereIF(input.VehicleId != null, u => u.VehicleId == input.VehicleId)
            .WhereIF(input.ImageUrl != null, u => u.ImageUrl == input.ImageUrl)
            .WhereIF(input.Sort != null, u => u.Sort == input.Sort)
            .LeftJoin<AppVehicleInfo>((u, vehicle) => u.VehicleId == vehicle.Id)
            .LeftJoin<SysFile>((u, vehicle, imageUrl) => u.ImageUrl == imageUrl.Id)
            .Select((u, vehicle, imageUrl) => new AppVehicleImageOutput
            {
                Id = u.Id,
                VehicleId = u.VehicleId,
                VehicleFkDisplayName = $"{vehicle.BrandId}",
                ImageUrl = u.ImageUrl,
                ImageUrlFkDisplayName = $"{imageUrl.FileName}",
                IsMain = u.IsMain,
                Sort = u.Sort,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取车辆图片表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取车辆图片表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppVehicleImage> Detail([FromQuery] QueryByIdAppVehicleImageInput input)
    {
        return await _appVehicleImageRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加车辆图片表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加车辆图片表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppVehicleImageInput input)
    {
        var entity = input.Adapt<AppVehicleImage>();
        return await _appVehicleImageRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新车辆图片表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新车辆图片表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppVehicleImageInput input)
    {
        var entity = input.Adapt<AppVehicleImage>();
        await _appVehicleImageRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除车辆图片表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除车辆图片表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppVehicleImageInput input)
    {
        var entity = await _appVehicleImageRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appVehicleImageRep.FakeDeleteAsync(entity);   //假删除
        //await _appVehicleImageRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除车辆图片表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除车辆图片表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAppVehicleImageInput> input)
    {
        var exp = Expressionable.Create<AppVehicleImage>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appVehicleImageRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _appVehicleImageRep.FakeDeleteAsync(list);   //假删除
        //return await _appVehicleImageRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAppVehicleImageInput input)
    {
        var vehicleIdData = await _appVehicleImageRep.Context.Queryable<AppVehicleInfo>()
            .InnerJoinIF<AppVehicleImage>(input.FromPage, (u, r) => u.Id == r.VehicleId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.BrandId}"
            }).ToListAsync();
        var imageUrlData = await _appVehicleImageRep.Context.Queryable<SysFile>()
            .InnerJoinIF<AppVehicleImage>(input.FromPage, (u, r) => u.Id == r.ImageUrl)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.FileName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "vehicleId", vehicleIdData },
            { "imageUrl", imageUrlData },
        };
    }
    
    /// <summary>
    /// 导出车辆图片表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出车辆图片表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAppVehicleImageInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAppVehicleImageOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "车辆图片表导出记录");
    }
    
    /// <summary>
    /// 下载车辆图片表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载车辆图片表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppVehicleImageOutput>(), "车辆图片表导入模板", (_, info) =>
        {
            if (nameof(ExportAppVehicleImageOutput.VehicleFkDisplayName) == info.Name) return _appVehicleImageRep.Context.Queryable<AppVehicleInfo>().Select(u => $"{u.BrandId}").Distinct().ToList();
            if (nameof(ExportAppVehicleImageOutput.ImageUrlFkDisplayName) == info.Name) return _appVehicleImageRep.Context.Queryable<SysFile>().Select(u => $"{u.FileName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入车辆图片表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入车辆图片表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAppVehicleImageInput, AppVehicleImage>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 车辆Id
                    var vehicleIdLabelList = pageItems.Where(x => x.VehicleFkDisplayName != null).Select(x => x.VehicleFkDisplayName).Distinct().ToList();
                    if (vehicleIdLabelList.Any()) {
                        var vehicleIdLinkMap = _appVehicleImageRep.Context.Queryable<AppVehicleInfo>().Where(u => vehicleIdLabelList.Contains($"{u.BrandId}")).ToList().ToDictionary(u => $"{u.BrandId}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.VehicleId = vehicleIdLinkMap.GetValueOrDefault(e.VehicleFkDisplayName ?? "");
                            if (e.VehicleId == null) e.Error = "车辆Id链接失败";
                        });
                    }
                    // 链接 图片URL
                    var imageUrlLabelList = pageItems.Where(x => x.ImageUrlFkDisplayName != null).Select(x => x.ImageUrlFkDisplayName).Distinct().ToList();
                    if (imageUrlLabelList.Any()) {
                        var imageUrlLinkMap = _appVehicleImageRep.Context.Queryable<SysFile>().Where(u => imageUrlLabelList.Contains($"{u.FileName}")).ToList().ToDictionary(u => $"{u.FileName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ImageUrl = imageUrlLinkMap.GetValueOrDefault(e.ImageUrlFkDisplayName ?? "");
                            if (e.ImageUrl == null) e.Error = "图片URL链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.VehicleId == null){
                            x.Error = "车辆Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ImageUrl == null){
                            x.Error = "图片URL不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.IsMain == null){
                            x.Error = "是否主图不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Sort == null){
                            x.Error = "排序不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppVehicleImage>>();
                    
                    var storageable = _appVehicleImageRep.Context.Storageable(rows)
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
